#include "resize.h"

#include <cassert> // assert
#include <limits> // std::numeric_limits

#include <unistd.h> // ftruncate off_t
#include <errno.h> // errno EFBIG EBADF

namespace simple::io
{

	ex_resize_result resize(const unique_handle& handle, std::size_t size) noexcept
	{
		assert(std::numeric_limits<off_t>::max() >= size);
		assert(handle != nullptr);
		int fd = static_cast<int>(static_cast<enum handle>(handle.get()));

		auto result = ::ftruncate(fd, size);
		if(-1 == result)
		{
			switch(errno)
			{
				case EFBIG: return size_limit_reached{errno};
				case EBADF: return not_write_handle{errno};
				default: return error{errno};
			}
		}

		return ex_resize_result{};
	}

} // namespace simple::io
